<?php

/**
 * 快递一百查询接口
 * @author chenshubo
 */
namespace App\Service\VendorClient\OrderLogisticSearchApi;

use App\Service\Code\Normal;
use App\Service\BaseService;
use function GuzzleHttp\json_encode;
use App\Service\TaskServer\TaskWorker;
use Service\AppService\IdService;
use App\Service\HttpServer\Http;

class NormalLogisticSearchApiClient extends BaseService
{

    private $account = 'kuaidi100';

    private $config = [];

  /**
     * 初始参数
     * @param obj $collection
     */
    public function __construct( $apiBody = [] ) 
    {
        $this->config = $apiBody;
    }

    /**
     * 查询物流单号
     * 
     * @param array  $params   
     */
    public function QueryLogisticByExpressSn($params = [])
    {
        $param = [
            'express_sn' => $params["express_sn"],
        ];
        $com = $this->autoCom($param['express_sn']);
        if (! empty($com) && is_array($com)) {
            $post_data["customer"] = $this->config['customer'];
            $key = $this->config['key'];
            $param['mobile'] = isset($param['mobile']) ? $param['mobile'] : "";
            $param['express_sn'] = preg_replace("/[\s\v" . chr(194) . chr(160) . "]+$/", "", $param['express_sn']);
            $param['express_sn'] = preg_replace("/^[\s\v" . chr(194) . chr(160) . "]+/", "", $param['express_sn']);
            foreach ($com as $ka => $va) {
                $comCode = $va['comCode'];
                $param_data = [
                    'com' => $comCode,
                    'num' => $param['express_sn'],
                    'phone' => $param['mobile'],
                    'from' => '',
                    'to' => '',
                    'resultv2' => ''
                ];
                $post_data['param'] = json_encode($param_data, true);
                $post_data["sign"] = md5($post_data["param"] . $key . $post_data["customer"]);
                $post_data["sign"] = strtoupper($post_data["sign"]);
                $temp = [];
                foreach ($post_data as $k => $v) {
                    $v = urlencode($v);
                    $temp[] = "{$k}={$v}";
                }
                
                $fields = implode("&", $temp);
                $requestParam = [
                    'method' => 'QueryLogisticByExpressSn',
                    'data' => $fields
                ];
                $res = $this->execute($requestParam);
                if ($res) {
                    return $res;
                    break;
                }
            }
            return Normal::returnCode(Normal::FAIL, "没找到对应快递！", "");
        } else {
            
            return Normal::returnCode(Normal::FAIL, "没查到对应快递信息，请检查运单号是否正确！", "");
        }
    }

    /**
     * 智能识别快递公司
     * 
     * @param string $express_sn            
     */
    public function autoCom($express_sn = '')
    {
        $key = $this->config['key'];
        $url = $this->config['autoNumberApi'] . '?num=' . $express_sn . '&key=' . $key;
        $res = Http::get($url);
        return json_decode($res, true);
    }

    /**
     * CURL请求
     * 
     * @param
     *            $params
     * @return mixed
     */
    public function execute($param = [])
    {
        if (empty($param['data'])) {
            return Normal::returnCode(Normal::FAIL, "数据不能为空");
        }
        
        $method = $param['method'];
        $url = $this->config['queryExpressSnApi'];
        
        $parameter = [
            [
                'tag' => $this->account . '_' . $method,
                'uid' => IdService::instance()->getOtherID(),
                'url' => $url,
                'data' => $param['data'],
                'method' => 'post',
                'format' => 'x-www-form-urlencoded',
                'header' => [
                    "Content-Type: application/x-www-form-urlencoded"
                ]
            ]
            
        ];
        
        $resTask = TaskWorker::instance()->addTask($parameter);
        $resTask = current($resTask);
        $res = $resTask['response']['result'];
        $resHttp = json_decode($res, true);
        if (isset($resHttp['message']) && $resHttp['message'] == 'ok') {
            return Normal::returnCode(Normal::SUC, "操作成功", $resHttp["data"]);
        }
        
        $message = isset($resHttp['message']) ? $resHttp['message'] : '请求失败';
        
        return Normal::returnCode(Normal::FAIL, $message);
    }
}
